<?php

class Model_HmEvent extends Zend_Db_Table_Abstract
{
	protected $_name = 'hm_event';
	protected $_primary = 'id';
	protected $_sequency = true;
	protected $_dependentTables = 'Model_HmEventTags';
	
	public function getAll()
	{
		if(FW_MODE == 'client') {
			$row = $this->fetchAll($this->select()->where('active = "Y"'));
		} else {
			$row = $this->fetchAll();
		}
		if(!$row) {
			throw new Exception('Could not fetch records.');
		}
		return $row->toArray();
	}
	
	public function getRow($id)
	{
		if(FW_MODE == 'client') {
			$row = $this->fetchRow('active = "Y" AND id = ' . (int)$id);
		} else {
			$row = $this->fetchRow('id = ' . (int)$id);
		}
		if(!$row) {
			throw new Exception('Could not fetch row '.(int)$id);
		}
		return $row->toArray();
	}
	
	public function getLast($order, $limit)
	{
		$row = $this->fetchAll(
							   $this->select()
											 ->where('active = "Y"')
											 ->order($order .' DESC')
											 ->limit($limit)
								);
		if(!$row) {
			throw new Exception('Could not fetch last row.');
		}
		
		return $row->toArray();
	}
	
	public function getNext($limit)
	{
		$row = $this->fetchAll(
							   $this->select()
							   				->where('active = "Y" AND date_start >= '.date('Y-m-d H:i:s'))
											->order('date_start ASC')
											->limit((int)$limit)
							   );
		if(!$row) {
			throw new Exception('Could not fetch next events.');
		}
		return $row->toArray();
	}
	
	public function addRow($data)
	{
		$row = $this->createRow($data);
		$row->save();
		if(!$row) {
			throw new Exception('Could not add row.');
		}
	}
	
	public function updateRow($id, $data)
	{
		$row = $this->update($data, 'id = '.(int)$id);
		if(!$row) {
			throw new Exception('Could not update row '.(int)$id);
		}
	}
	
	public function deleteRow($id)
	{
		$row = $this->delete('id = '.(int)$id);
		if(!$row) {
			throw new Exception('Could not delete row '.(int)$id);
		}
	}
}